<!--it
 * @Date: 2023-02-27 20:33:27
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-19 20:02:58
 * @FilePath: \A19\frontend\src\components\MyCourse.vue
-->
<template>
  <div id="MyCourse">

    <div class="search">
          <div class="search-tit"> 
            <div class="tit">我的课程</div>
            <ElInput style="width: 210px;" size="default" v-model="search" placeholder="Search"></ElInput>
          </div>
        
          
          <el-button @click="addCourse" round class="add-button" v-if="poss" icon="circlePlus">
            添加课程
          </el-button>
          <el-button @click="selectCourse" round class="add-button" v-else icon="circlePlus">
            添加选课
          </el-button>

      </div>
    <div style="height: 100%;" v-if="myCourses.length !== 0">
      
      

      <div class="course-list">
        <div 
          class="course-item"
          :key="course._id"
          v-for="course in filteredCourse"
        >
          <div class="info">
            <img class="cover" :src="conf.server + course.cover" alt="course" />
            <div class="name">
            {{ course.name }}
            </div>
          </div>
          
          <div class="controllers">
            <ElButton  plain @click="goToCourse(course._id)">进入课堂</ElButton>
          </div>
        </div>

      </div>
      
    </div>
    <div class="none" v-else>
      <div class="wrapper">暂无课程</div>
    </div>
  </div>

  <ElDialog
    v-model="dialogVisiable"
    title="添加课程"
    width="40%"
    :show-close="false"
    custom-class="dia"
  >
    <ElForm ref="form2Instance" :model="form2" :rules="form2Rule" :label-width="100">
      <el-form-item label="课程封面" prop="portrait" error="">
        <el-upload
          class="user-portrait"
          action="#"
          :on-change="selected"
          :show-file-list="false"
          :http-request="async () => {}"
        >
          <img :src="form2.cover.fileDate" class="avatar" />
          <el-icon>
            <Picture />
          </el-icon>
          <!-- <i class="el-icon-picture-outline"></i> -->
        </el-upload>
      </el-form-item>
      <ElFormItem label="课程名称" prop="name">
        <ElInput v-model="form2.name"></ElInput>
      </ElFormItem>
      <ElFormItem label="课程介绍" prop="introduction">
        <ElInput type="textarea" v-model="form2.introduction"></ElInput>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="clear">取消</el-button>
        <el-button type="primary" @click="create"> 创建课程 </el-button>
      </span>
    </template>
  </ElDialog>

  <el-dialog
    v-model="dialogVisible"
    title="选课"
    width="40%"
    :show-close="false"
    class="selectDia"
  >
    <el-table height="350" :data="tableDataFilter" style="width: 100%;" highlight-current-row @current-change="handleCurrentChange">
      <el-table-column prop="name" label="课程名称" >
        <template #header>
          <el-input v-model="searchName"  placeholder="课程名称" />
        </template>
      </el-table-column>
      <el-table-column prop="teacher.name" label="教师" >
        <template #header>
          <el-input v-model="searchTea"  placeholder="教师" />
        </template>
      </el-table-column>
      <el-table-column prop="school" label="学校" />
    </el-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelSelect">取消</el-button>
        <el-button type="primary" @click="confirmSelect">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import router from "@/route";
import { ref, onMounted, provide, computed } from "vue";
import { useClientStore } from "../pinia/stores/client";
import { courses } from "../shared/types/courses";
import { storeToRefs } from "pinia";
import { ElSubMenu, FormInstance, FormRules, UploadFile } from "element-plus";
import { conf } from "@/utils/conf";
const store = useClientStore();
const { client, currentUser } = store;
const { currentCourseId } = storeToRefs(store);
const poss = computed(() => {
  return currentUser.role === "teacher";
});

const search = ref('')
const myCourses = ref(new Array<courses>());
const filteredCourse = computed(() =>{
  const regExp = new RegExp(search.value)
  return myCourses.value.filter(c => regExp.test(c.name))
})
const goToCourse = (id: string) => {
  currentCourseId.value = id;
  router.push({
    name: "homework",
    params: {
      courseId: id,
    },
  });
};

let loadingInstance: any;
const dialogVisiable = ref(false);
const form2 = ref({
  cover: {
    fileDate: /*base64*/ conf.server + "/cover.jpg",
    fileType: undefined as undefined | string,
    fileUploadDate: new Uint8Array(),
  },
  name: "",
  introduction: "",
});
const form2Rule: FormRules = {
  name: {
    required: true,
    message: "请填写课程名称",
    trigger: "blur",
  },
};
const form2Instance = ref<FormInstance>();
const addCourse = () => {
  dialogVisiable.value = true;
};
const create = async () => {
  loadingInstance = ElLoading.service({
    target: ".dia",
  });
  const ret = await client.callApi("Create/CreateCourse", {
    name: form2.value.name,
    introduction: form2.value.introduction,
    cover: form2.value.cover.fileType
      ? {
          fileDate: form2.value.cover.fileUploadDate,
          fileType: form2.value.cover.fileType,
        }
      : undefined,
  });
  if (ret.isSucc) {
    ElMessage.success("创建成功");
    myCourses.value.unshift(ret.res.course);
    clear();
  }
  loadingInstance.close();
};

const selected = ({ raw, status }: UploadFile) => {
  if (status !== "success") return;
  if (raw === undefined) return;
  if (raw.type !== "image/jpeg" && raw.type !== "image/png") {
    ElMessage.error("上传封面图片只能是 JPG 或 PNG 格式!");
    return;
  } else if (raw.size / 1024 / 1024 > 2) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
    return;
  }

  form2.value.cover.fileType = raw.type;
  const reader1 = new FileReader();
  const reader2 = new FileReader();
  reader1.addEventListener("load", () => {
    form2.value.cover.fileDate = reader1.result as string;
  });
  reader1.readAsDataURL(raw);
  reader2.addEventListener("load", () => {
    form2.value.cover.fileUploadDate = new Uint8Array(reader2.result as ArrayBuffer);
  });
  reader2.readAsArrayBuffer(raw);
};
const clear = () => {
  form2.value = {
    cover: {
      fileDate: /*base64*/ conf.server + "/cover.jpg",
      fileType: undefined as undefined | string,
      fileUploadDate: new Uint8Array(),
    },
    name: "",
    introduction: "",
  };
  dialogVisiable.value = false;
};


const dialogVisible = ref(false)
const selectCourse = () =>{
  dialogVisible.value = true
}
let selectedCourse:any;
const handleCurrentChange = (currentRow:any,oldCurrentRow:any) =>{
  selectedCourse = currentRow
}
const confirmSelect = async () =>{
  loadingInstance = ElLoading.service({
    target:'.selectDia'
  })
  if(!selectedCourse){
    ElMessage.warning('请选择一个课程')
    loadingInstance.close()
    return 
  }
  const ret = await client.callApi('Select/SelectCourse',{
    courseId:selectedCourse._id
  })
  if(ret.isSucc){
    const ret = await client.callApi(
      currentUser.role === "student" ? "Get/GetSelectedCourses" : "Get/GetCreatedCourses",
      {}
    );
    if (ret.isSucc) {
      myCourses.value = ret.res.courses;
      ElMessage.success('选课成功')
      cancelSelect()
    }
  }
  loadingInstance.close()
}
const cancelSelect = () =>{
  dialogVisible.value = false
}
const tableData = ref(new Array<any>)
const tableDataFilter = computed(() =>{
  try {
    const name = new RegExp(searchName.value)
    const tea = new RegExp(searchTea.value)

    return tableData.value
    .filter(v => tea.test(v.teacher.name) && name.test(v.name) )
  } catch (error) {
    return tableData.value
  }
})
const searchName = ref('')
const searchTea = ref('')

onMounted(async () => {
  loadingInstance = ElLoading.service({
    target: "#app",
  });
  const ret = await client.callApi(
    currentUser.role === "student" ? "Get/GetSelectedCourses" : "Get/GetCreatedCourses",
    {}
  );
  if (ret.isSucc) {
    myCourses.value = ret.res.courses;
  }

  const ret2 = await client.callApi('Search/SearchCourses',{
    name:''
  })
  if(ret2.isSucc){
    tableData.value = ret2.res.courses
  }

  loadingInstance.close();
});
</script>

<style lang="less" scoped>
#MyCourse {
  height: 100%;
  width: 100%;
  position: relative;
  .search{
    height: 60px;
    line-height: 60px;
    padding-left: 20px;
    padding-right: 50px;
    background-color: #f2f8ff48;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .search-tit{
      display: flex;
      align-items: center;
      .tit{
        margin-right: 20px;
        font-size: 20px;
        font-weight: bold;
        color: #909292b5;
      }
    }
    .add-button{
      
    }
  }
  .course-list{
    height: calc(100% - 60px);
    width: 100%;
    padding: 0px 10px;
    overflow: auto;

    .course-item{
      position: relative;
      height: 150px;
      width: 100%;
      background-color: #f2f8ff47;
      border-radius: 10px;
      margin: 10px 0;
      cursor: pointer;
      display: flex;
      justify-content: space-between;
      align-items: center;
      &:nth-of-type(2n){
        background-color: #f2f8ff26;
      }
      &:hover{
        background-color: #f2f8ff9c;
      }

      .info{
        height: 80%;
        margin-left: 30px;
        display: flex;
        align-items: center;
        .cover{
          height: 100%;
          aspect-ratio: 16 /9;
          object-fit: cover;
          border-radius: 5px;
        }
        .name{
          font-size: 20px;
          text-shadow: 0 2px 10px rgba(0,0,0,0.3);
          color: #666666;
          margin-left: 20px;
        }
      }

     
      .controllers{
        padding: 0 50px;
      }
    }
  }
}

@fontColor: #a6a6a6;
.none {
  height: calc(100% - 60px);
  width: 100%;
  background-color: #f2f4f747;
  .wrapper {
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    height: 100px;
    width: 500px;
    background-color: white;
    border-radius: 20px;
    margin: auto auto;
    color: #a6a6a6;
    text-align: center;
    line-height: 100px;
  }
}

.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  width: 860px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
  cursor: pointer;

  &:hover {
    background: #f2f8ff;
  }
}

// img {
//   width: 180px;
//   position: relative;
//   left: -330px;
//   border-radius: 4px;
// }



.dia {
  .user-portrait {
    position: relative;
    font-size: 14px;
    box-sizing: border-box;
    outline: none;
    vertical-align: middle;
    border: 0;
    margin: 0;
    padding: 0;
    height: 100px;
    width: 150px;
    border-radius: 50%;
    //  overflow: hidden;

    i {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
      height: 50px;
      width: 50px;
      text-align: center;
      line-height: 50px;
      font-size: 35px;
      color: #fff;
      opacity: 0;
      transition: opacity 0.3s ease;
    }

    img {
      height: 100px;
      width: 150px;
      display: block;
      transition: filter 0.3s ease;
      left: 0;
      object-fit: cover;
    }

    &:hover {
      img {
        filter: brightness(0.8);
      }

      i {
        opacity: 0.9;
      }
    }
  }
}


</style>

<style lang="less">
.selectDia{
  .el-table__row{
    cursor: pointer;
  }
}
</style>